package com.zn.product;


import com.google.gson.Gson;
import com.zn.DBUtil;
import com.zn.product.model.Product;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/product_List.do")
public class ProductListServlet  extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from tb_product order by create_time desc limit 10";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ArrayList list = new ArrayList();
            while(rs.next()){
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setDescription(rs.getString("description"));
                product.setMarket_price(rs.getDouble("market_price"));
                product.setSell_price(rs.getDouble("sell_price"));
                product.setPicture(rs.getString("picture"));
                list.add(product);
                product = null;
            }
            resp.setContentType("application/json;charset=utf-8");

            Gson gson = new Gson();
            String result = gson.toJson(list);
            resp.getWriter().println(result);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.closeResource(conn, ps, rs);
        }

    }
}